from tkinter import filedialog
from datetime import datetime, timezone
import os

filepath = filedialog.askopenfilename(filetypes=[('txt', '*.txt')])

with open(filepath, 'r', encoding='utf-8', errors='ignore') as file:
    lines = file.readlines()

sub = '00000197'
all_data = []  # 存储所有解析出的数据点
existing_times = set()
initial_data = []
FRI_line = "[2025-06-30 14:42:48   ('220.205.248.166', 6599)]ASC:    +RESP:GTFRI,8020070501,867564050610267,GB100CG,13916,10,1,1,34.3,107,28.7,117.225592,31.854298,20250630064238,0460,0001,DF5B,05A06A10,01,17,7794.3,0000528:20:04,,,,100,220000,,,,20250630064240,028E$"


# 如果文件已存在，读取已有时间戳
if os.path.exists('fri_convert.txt'):
    with open('fri_convert.txt', 'r') as f:
        for line in f:
            parts = line.strip().split(',')
            if parts:
                existing_times.add(parts[0])


# 解析所有数据点
for line in lines:
    #print(line)
    start_index = 0
    while True:
        pos = line.find(sub, start_index)
        #print(pos)  
        if pos == -1:
            break
 
        # 确保有足够的数据长度
        if pos + 34 > len(line):
            break
        time_str = line[pos:pos+16]
        lon_str = line[pos+18:pos+26]
        lat_str = line[pos+26:pos+34]
        angle_str = line[pos+38:pos+42]
        speed_str = line[pos+44:pos+48]
        
        try:
            # 转换时间戳
            time_bytes = bytes.fromhex(time_str)
            timestamp_ms = int.from_bytes(time_bytes, 'big')
            #print(timestamp_ms)
            utc_time = datetime.fromtimestamp(timestamp_ms / 1000, timezone.utc)
            #print(utc_time)
            # 转换经纬度
            lon_bytes = bytes.fromhex(lon_str)
            lat_bytes = bytes.fromhex(lat_str)
            angle_bytes = bytes.fromhex(angle_str)
            speed_bytes = bytes.fromhex(speed_str)
            lon_value = int.from_bytes(lon_bytes, 'big', signed=True) / 1e7
            lat_value = int.from_bytes(lat_bytes, 'big', signed=True) / 1e7
            speed_value = int.from_bytes(speed_bytes)
            angle_value = int.from_bytes(angle_bytes)
            
            # 格式化时间作为键
            time_key = utc_time.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]  # 精确到毫秒
            data_line = f"{time_str} {utc_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]} {lon_value} {lat_value} {speed_value} {angle_value}\n"
            #print(data_line)
            initial_data.append(data_line)
            
            # 添加到数据集（如果时间戳不存在）
            if time_key not in existing_times:
                all_data.append((utc_time, lon_value, lat_value,speed_value,angle_value))
                existing_times.add(time_key)
            
        except (ValueError, IndexError) as e:
            print(f"解析错误位置 {pos}: {e}")
        
        # 移动到下一个位置
        start_index = pos + 1
    #print("next line\n")
# 按时间排序所有数据点

with open('initial.txt', 'w') as f:
    f.writelines(initial_data)
all_data.sort(key=lambda x: x[0])

# 写入排序后的数据
with open('data_convert.txt', 'w') as f:  # 使用追加模式，但实际每次都会覆盖旧数据
    # 如果文件已存在，先清空（因为我们已读取了现有时间戳）
    f.seek(0)
    f.truncate()
    
    # 写入排序后的数据
    for utc_time, lon_value, lat_value, speed_value, angle_value in all_data:
        time_str = utc_time.strftime("%Y-%m-%d %H:%M:%S")  # 精确到毫秒
        f.write(f"{time_str},{speed_value},{angle_value},{lon_value},{lat_value}\n")



with open('data_convert.txt', 'r', encoding='utf-8', errors='ignore') as file:
    lines = file.readlines()
    
convert_fri_lines = []

for line in lines:
    time_str = line.split(',')[0]
    dt = datetime.fromisoformat(time_str)
    convert_time = dt.strftime('%Y%m%d%H%M%S')
    parts = line.split(',')
    lon = parts[3]
    lat = parts[4]
    speed =parts[1]
    angle = parts[2]
    fri_parts = FRI_line.split(',')
    fri_parts[14] = convert_time.strip()  # 替换时间
    fri_parts[12] = lon.strip()          # 替换经度
    fri_parts[13] = lat.strip()  # 替换纬度
    fri_parts[9] = speed.strip()
    fri_parts[10] = angle.strip()
    new_fri_line = ','.join(fri_parts)
    #print(new_fri_line)
    convert_fri_lines.append(new_fri_line+ '\n')

with open('fri_convert.txt', 'w') as f:
    f.writelines(convert_fri_lines)
